آموزش نصب JWT بر روی lumen

آموزش نصب JWT بر روی lumen

JSON Web Token  یا JWT یک استاندار وب برای فشرده سازی و انتقال امن اطلاعات بین مقاصد مختلف توسط یک رشته ی json  می باشد.در روش JWT از یک امضاء دیجیتال استفاده می شود که توسط یک کلید مخفی و یک جفت کلید خصوصی و عمومی قابل امضا می باشند.

JSON Web Token  یا JWT یک استاندار وب برای فشرده سازی و انتقال امن اطلاعات بین مقاصد مختلف توسط یک رشته ی json  می باشد.

در روش JWT از یک امضاء دیجیتال استفاده می شود که توسط یک کلید مخفی و یک جفت کلید خصوصی و عمومی قابل امضا می باشند.

در لاراول و لومن می توانید با استفاده از پکیج های ایجاد شده JWT را بر روی پروژه ی خود فعال کرد. در این این آموزش ما قصد داریم روش فعال سازی JWT بر روی فریم وورک Lumen را پیاده سازی کنیم:

ابتدا فریم وورک لومن را با استفاده از دستور زیر نصب کنید:

composer create-project laravel/lumen ./jwt-example

پس از نصب lumen دستور زیر را برای نصب پکیج tymon/jwt-auth در خط فرمان پروژه اجرا نمایید:

composer require tymon/jwt-auth:"^1.0@dev"


فایل bootstrap/app.php را باز کنید و دو تغییر زیر را انجام دهید:

// Uncomment this line
$app->register(App\Providers\AuthServiceProvider::class);

// Add this line
$app->register(Tymon\JWTAuth\Providers\LumenServiceProvider::class);

 

در همین فایل Middleware مربوط به Auth را از حالت کامنت خارج کنید:

$app->routeMiddleware([
    'auth' => App\Http\Middleware\Authenticate::class,
]);

 

در مرحله بعد یک فایل پیکربندی  ایجاد خواهیم کرد که بتوانیم برای استفاده از درایور JWT از آن استفاده کنیم. 

یک فایل جدید بنام config/auth.php ایجاد  و محتویات زیر را در آن قرار دهید:  


<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Authentication Defaults
    |--------------------------------------------------------------------------
    |
    | This option controls the default authentication "guard" and password
    | reset options for your application. You may change these defaults
    | as required, but they're a perfect start for most applications.
    |
    */

    'defaults' => [
        'guard' => env('AUTH_GUARD', 'api'),
    ],

    /*
    |--------------------------------------------------------------------------
    | Authentication Guards
    |--------------------------------------------------------------------------
    |
    | Next, you may define every authentication guard for your application.
    | Of course, a great default configuration has been defined for you
    | here which uses session storage and the Eloquent user provider.
    |
    | All authentication drivers have a user provider. This defines how the
    | users are actually retrieved out of your database or other storage
    | mechanisms used by this application to persist your user's data.
    |
    | Supported: "session", "token"
    |
    */

    'guards' => [
        'api' => [
            'driver' => 'jwt',
            'provider' => 'users'
        ],
    ],

    /*
    |--------------------------------------------------------------------------
    | User Providers
    |--------------------------------------------------------------------------
    |
    | All authentication drivers have a user provider. This defines how the
    | users are actually retrieved out of your database or other storage
    | mechanisms used by this application to persist your user's data.
    |
    | If you have multiple user tables or models you may configure multiple
    | sources which represent each model / table. These sources may then
    | be assigned to any extra authentication guards you have defined.
    |
    | Supported: "database", "eloquent"
    |
    */

    'providers' => [
        'users' => [
            'driver' => 'eloquent',
            'model'  => \App\User::class,
        ],
    ],

    /*
    |--------------------------------------------------------------------------
    | Resetting Passwords
    |--------------------------------------------------------------------------
    |
    | Here you may set the options for resetting passwords including the view
    | that is your password reset e-mail. You may also set the name of the
    | table that maintains all of the reset tokens for your application.
    |
    | You may specify multiple password reset configurations if you have more
    | than one user table or model in the application and you want to have
    | separate password reset settings based on the specific user types.
    |
    | The expire time is the number of minutes that the reset token should be
    | considered valid. This security feature keeps tokens short-lived so
    | they have less time to be guessed. You may change this as needed.
    |
    */

    'passwords' => [
        //
    ],

];

 

با دقت در کد بالا متوجه خواهید شد که ما درایو مربوط به api را بر روی jwt ست کرده ایم. بنابراین درخواست هایی که به گارد api ارسال خواهند شد بصورت خودکار با jwt احراز هویت خواهند شد.

 

حال باید در مدل یا مدل های مورد نظر ازپیاده سازی JWT را انجام دهیم. ما قصد داریم مدل User از JWT استفاده کند. بنابراین مدل ما بصورت زیر خواهد بود:

<?php

namespace App;

use Illuminate\Auth\Authenticatable;
use Laravel\Lumen\Auth\Authorizable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;
use Tymon\JWTAuth\Contracts\JWTSubject;

class User extends Model implements JWTSubject, AuthenticatableContract, AuthorizableContract
{
    use Authenticatable, Authorizable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email',
    ];

    /**
     * The attributes excluded from the model's JSON form.
     *
     * @var array
     */
    protected $hidden = [
        'password',
    ];

    public function getJWTIdentifier()
    {
        return $this->getKey();
    }

    public function getJWTCustomClaims()
    {
        return [];
    }
}

 

همانطور که در بالا می بینید مدل User کلاس JWTSubject را implements کرده است. همچنین شما باید AuthenticatableContract, AuthorizableContract را نیز implements کرده و trait های Authenticatable, Authorizable را نیز در مدل خود فراخوانی کنید.

همچنین دو متد جدید با نام های getJWTIdentifier و getJWTCustomClaims نیز به مدل اضاف خواهد شد که اگر قصد استفاده از jwt در دیگر زبان ها همچون nodejs را دارید برای بازیابی کاربر خود می توانید در متد getJWTCustomClaims برخی اطلاعات کاربر لاگین شده مانند user_id و... را قرار دهید.

 

حال برای لاگین می توانید یک contraller  ایجاد و مطابق زیر عملیات احراز هویت کاربر را انجام دهید:

namespace App\Http\Controllers;

use Illuminate\Support\Facades\Auth;
use App\Http\Controllers\Controller;

class AuthController extends Controller
{
    /**
     * Create a new AuthController instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth:api', ['except' => ['login']]);
    }

    /**
     * Get a JWT via given credentials.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function login()
    {
        $credentials = request(['email', 'password']);

        if (! $token = auth()->attempt($credentials)) {
            return response()->json(['error' => 'Unauthorized'], 401);
        }

        return $this->respondWithToken($token);
    }

    /**
     * Get the authenticated User.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function me()
    {
        return response()->json(auth()->user());
    }

    /**
     * Log the user out (Invalidate the token).
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function logout()
    {
        auth()->logout();

        return response()->json(['message' => 'Successfully logged out']);
    }

    /**
     * Refresh a token.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function refresh()
    {
        return $this->respondWithToken(auth()->refresh());
    }

    /**
     * Get the token array structure.
     *
     * @param  string $token
     *
     * @return \Illuminate\Http\JsonResponse
     */
    protected function respondWithToken($token)
    {
        return response()->json([
            'access_token' => $token,
            'token_type' => 'bearer',
            'expires_in' => auth()->factory()->getTTL() * 60
        ]);
    }
}

 

متد login در این کنترلر ایمیل و پسوورد کاربر را گرفته سپس با استفاده از دستور auth()->attempt($credentials) عملیات احراز هویت را انجام، و درصورت موفق بود عملیات یک توکن برگشت خواهد داد که می توانید از توکن برگشتی برای دسترسی به دیگر روت های حفاظت شده استفاده نمایید.

 

برای ایجاد secrect key مخصوص JWT کد زیر را در خط فرمان خود فراخوانی کنید:

php artisan jwt:secret

 

حال می توانید  به راحتی از JWT استفاده کنید. برای نمونه شما می توانید middleware مربوط به JWT را که در بالا تعریف کرده ایم بصورت زیر به روت یا روت های خود داده تا عملیات احراز هویت انجام شود.

 

$app->group(['middleware' => 'auth:api'], function($app)
{
    $app->get('/test', function() {
        return response()->json([
            'message' => 'Hello World!',
        ]);
    });
});

 

فراموش نکنید که tymon-jwt از token نوع Bearer استفاده می کند. و شما برای پس از لاگین و دریافت توکن، برای دسترسی به روت های حفاظت شده برای نمونه باید توکن خود را در هدر درخواست و بصورت زیر ارسال نمایید:

"Authorization: Bearer <token>"

 

 

امیدوارم این مطلب برای شما مفید واقع شده باشه. درصورتی که سوالی دارید یا در زمان نصب با مشکلی مواجه شدید از بخش نظرات مشکل خودتون رو ارسال کنید تا در کوتاه ترین زمان ممکن پاسخ بدیم.

 


دسته بندی ها:

لاراول

ارسال نظر

برای اطلاع از پاسخ به نظر شما می توانید ایمیل یا شماره موبایل خود را وارد نمایید. *

ایمیل و شماره موبایل شما کاملا مخفی خواهد ماند و در سایت نمایش داده نخواهد شد. *

اگر نظری برای این مطلب ارسال شد از طریق ایمیل مرا اطلاع بده!
لسیت نظرات
هنوز برای این مطلب نظری ارسال نشده است!